﻿using my_webapi_demo.Common;
using my_webapi_demo.Exceptions;

namespace my_webapi_demo.Auth;

[HuaskyService]
public class UserSession
{
    readonly HttpRequest _request;

    public UserSession(IHttpContextAccessor httpContext)
        : this(httpContext.HttpContext?.Request)
    {
    }

    public UserSession(HttpRequest request)
    {
        _request = request;
    }

    static SessionParser[] _parsers;

    static UserSession()
    {
        _parsers =
        [
            AuthSession.GetSessionData
        ];
    }

    /// <summary>
    /// 获取会话信息期（较轻量级），无效会话抛异常
    /// </summary>
    public SessionData GetSessionData(bool ensureLogin = true)
    {
        return GetSessionData(_request, ensureLogin);
    }

    public static SessionData GetSessionData(HttpRequest request, bool ensureLogin = true)
    {
        var session = getSession(request);
        if (ensureLogin && session.State != AuthState.Normal)
        {
            throw new AuthException(session.State);
        }

        return session;
    }

    static SessionData getSession(HttpRequest request)
    {
        try
        {
            foreach (var parser in _parsers)
            {
                var session = parser(request);
                if (session != null)
                {
                    return session;
                }
            }
        }
        catch (Exception e)
        {
            //正常流程不应该抛异常，需要定位异常原因
            LoggerHelper.Error(e);
        }

        return SessionData.NotLogin;
    }

    //不返回空，空状态返回NotLogin
    delegate SessionData SessionParser(HttpRequest req);
}
